//
//  WaterFallFlowLayout.swift
//  SwiftScrollBanner
//
//  Created by shenjie on 2021/2/19.
//

import UIKit

protocol YHWaterFallLayoutDelegate: NSObjectProtocol {
    func waterFlowLayout(_ waterFlowLayout: YHWaterFallFlowLayout, itemWidth indexPath: IndexPath) -> CGFloat
}

class YHWaterFallFlowLayout: UICollectionViewFlowLayout {

    weak var delegate: YHWaterFallLayoutDelegate?

    // 布局数组
    fileprivate lazy var layoutAttributeArray: [UICollectionViewLayoutAttributes] = []
    // 当前宽度
    fileprivate var currentWidth: CGFloat = 0
    fileprivate var maxHeight: CGFloat = 0
    override func prepare() {
        super.prepare()
        // 计算每个 Cell 的宽度
        let itemHeight = 26
        // Cell 数量
        let itemCount = collectionView!.numberOfItems(inSection: 0)
        // 最小高度索引
        // 遍历 item 计算并缓存属性
        let width = collectionView!.bounds.width
        maxHeight = minimumLineSpacing
        for i in layoutAttributeArray.count ..< itemCount {
            
            currentWidth += (minimumInteritemSpacing)
            let indexPath = IndexPath(item: i, section: 0)
            let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            // 获取动态宽度
            let itemWidth = delegate?.waterFlowLayout(self, itemWidth: indexPath)
            
            // 计算该索引的 X 坐标
            var itemX = 0.0
            let current = currentWidth + (itemWidth ?? 10.0) + minimumInteritemSpacing
            if current > width {
                itemX = minimumInteritemSpacing
                currentWidth = (minimumInteritemSpacing + (itemWidth ?? 10.0))
                maxHeight += (CGFloat(itemHeight) + minimumLineSpacing)
            } else {
                itemX = currentWidth + minimumInteritemSpacing
                currentWidth += (minimumInteritemSpacing + (itemWidth ?? 10.0))
            }
            // 获取该列的 Y 坐标
            let itemY = maxHeight
            
            // 赋值新的位置信息
            attr.frame = CGRect(x: itemX, y: itemY, width: (itemWidth ?? 10.0), height: CGFloat(itemHeight))
            // 缓存布局属性
            layoutAttributeArray.append(attr)
            // 更新最短高度列的数据
        }
        maxHeight += (CGFloat(itemHeight) + minimumLineSpacing)
    }
}

extension YHWaterFallFlowLayout {
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // 返回相交的区域
        return layoutAttributeArray.filter {
            $0.frame.intersects(rect)
        }
    }
    
    override var collectionViewContentSize: CGSize {
        return CGSize(width: collectionView!.bounds.width, height: maxHeight)
    }
}
